#include <QIODevice>
#include <QFile>
#include <QtDebug>
#include <QThread>
#include <QTextStream>

#include "file_processing.h"
#include "file_data_division_processing.h"
#include "file_data_read_processing.h"
#include "../data/track_id_data_integrated.h"


File_processing::File_processing(QObject *parent):
    QObject(parent),
    division_process_(new File_data_division_processing()),
    read_process_(new File_data_read_processing())
{
    init_connections();
}

File_processing::~File_processing()
{
    data_division_thread_.quit();
    data_division_thread_.wait();

    data_read_thread_.quit();
    data_read_thread_.wait();

    // 当division_process_和File_processing在同一个线程中，说明division_process_没有迁移到子线程，
    // 需要手动释放division_process_消耗的资源
    if (thread() == division_process_->thread()) {
        delete  division_process_;
        division_process_ = nullptr;
    }

    // 原因同division_process_
    if (thread() == read_process_->thread()) {
        delete read_process_;
        read_process_ = nullptr;
    }
}

void File_processing::open_file_to_split_data(QString file_name_with_path)
{
    // Test
//    qDebug()<< "File_processing++++: " << (quint64) QThread::currentThreadId() << Qt::endl;

    start_data_process_thread(data_division_thread_, division_process_);

    emit sig_file_name_with_path(file_name_with_path);
}

void File_processing::open_file_to_read_data(QStringList files_name_with_path)
{
    start_data_process_thread(data_read_thread_, read_process_);

    emit sig_file_name_with_path_to_read_data(files_name_with_path);
}

void File_processing::init_connections()
{
    // 传递打开的文件名，将文件的不同类型数据保存到不通文件中
    connect(this, &File_processing::sig_file_name_with_path,
            division_process_, &File_data_division_processing::sig_open_file);

    // 子线程关闭后通知
    connect(&data_division_thread_, &QThread::finished,
            division_process_, &File_data_division_processing::deleteLater);

    connect(this,
            static_cast<void (File_processing::*)(QStringList)>(&File_processing::sig_file_name_with_path_to_read_data),
            read_process_,
            static_cast<void (File_data_read_processing::*)(QStringList)>(&File_data_read_processing::sig_open_file));

    connect(&data_read_thread_, &QThread::finished,
            read_process_, &File_data_read_processing::deleteLater);

    connect(read_process_,
            static_cast<void (File_data_read_processing::*)(Track_id_data_integrated*)>(&File_data_read_processing::sig_integrated_data),
            this,
            static_cast<void (File_processing::*)(Track_id_data_integrated*)>(&File_processing::sig_integrated_data));
}

void File_processing::start_data_process_thread(QThread& thread, QObject* process)
{
    // 子线程未启动，将变量移动到子线程，启动子线程
    if ( !thread.isRunning()) {
        process->moveToThread(&thread);
        thread.start();
    }
}
